﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;

using JoyServer.Input;

namespace JoyServer.Net
{
	/// <summary>
	/// パケット組み立て用クラス
	/// </summary>
	class PacketBuilder
	{
		/// <summary>
		/// ジョイスティックのデータ送信用パケットを組み立てる
		/// </summary>
		/// <param name="joystickNumber"></param>
		/// <returns></returns>
		public static Packet createJoystickDataPacket(uint joystickNumber)
		{
			Joystick joystick = Global.input.read(joystickNumber);

			if (joystick == null || joystickNumber >= 100)
			{
				Packet errorPacket = new Packet();
				errorPacket.type = 1;

				errorPacket.data.writeByte(0);
				errorPacket.data.writeByte(0);
				for (int i = 0; i < 10; i++)
				{
					errorPacket.data.writeUnsignedByte(0);
				}
				return errorPacket;
			}

			Packet packet = new Packet();
			packet.type = joystickNumber;
			packet.data.writeByte((sbyte)joystick.x);
			packet.data.writeByte((sbyte)joystick.y);
			for (int i = 0; i < 10; i++)
			{
				packet.data.writeUnsignedByte((byte)(joystick.buttons[i] >> 7));
			}
			return packet;
		}

		/// <summary>
		/// デバイスの名前のリストが入ったパケットを組み立てる
		/// </summary>
		/// <returns></returns>
		public static Packet createDeviceListPacket()
		{
			List<String> names = Global.input.getDeviceNames();

			Packet packet = new Packet();
			packet.type = SystemPacketType.DEVICE_LIST;
			packet.data.writeByte((sbyte)names.Count);

			foreach (String name in names)
			{
				packet.data.writeUTF(name);
			}
			return packet;
		}

		/// <summary>
		/// クライアントの接続確認用パケットを組み立てる
		/// </summary>
		/// <returns></returns>
		public static Packet createPingPacket()
		{
			Packet packet = new Packet();
			packet.type = SystemPacketType.PING;
			return packet;
		}
	}
}
